local CommonOHOH = _G.CommonOHOH;

local M = CommonOHOH.class.new(script, CommonOHOH.files.BaseComponent());

local CellClass=require(script.Parent.Parent.Cell)

function M.new(...)
	return M(...);
end;


function M.ctor(self,parent)
    self.List={}

    M.super.ctor(self,parent);


    self.CellPerfab=self.parent:GetCellPerfab()
    self.CellPerfab.Visible=false

    self.parent.AddBroDataEvent:Connect(function(data)
        self:AddCell(data)
    end)

    self.ShowEvent=self.parent.ActiveBroEventEvent
end;


function M.dtor(self)
	M.super.dtor(self);
end;


function M.AddCell(self,data)
    assert(data.id,"data==nil")
    local cell_inst=self.CellPerfab:Clone()
    cell_inst.Parent= self.CellPerfab.Parent
    cell_inst.Visible=true
    local cell=CellClass.new(cell_inst,data.id,data.level)

    cell.ActiveEvent:Connect(function()
        self:ActiveCell(cell:GetId())
    end)

    local guid=cell:GetId()

    self.List[guid]= {
        ui=cell,
        data=data
    }

    
    data.UpdateEvent:Connect(function()
        cell:Update(data.headIcon,data.isEquip,data.level,data.isLock)
    end)

    data.DtorEvent:Connect(function()
        if self.selectCell==cell then
            self.selectCell=nil
        end
        cell:dtor()
        self.List[guid]=nil
    end)

end

function M.ActiveFristCell(self)

    local list={}
    for _,UiInfo in pairs(self.List) do
        table.insert(list,UiInfo.ui)
    end

    if #list>0 then
        table.sort(list,function(a,b)
            return   a:getSortId()>b:getSortId()
        end)

        self:ActiveCell(list[1]:GetId())
    else
    end
end


function M.ActiveCell(self,id)

    local cell=self.List[id].ui
    if  self.selectCell then
        self.selectCell:NoActive()
    end
    self.selectCell=cell
    self.selectCell:Active()
    self.ShowEvent:Action(self.List[id].data)


end


return M